package com.atguigu.bigdata.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bigdata.gmall.realtime.app.BaseAppV1;
import com.atguigu.bigdata.gmall.realtime.bean.UserLoginBean;
import com.atguigu.bigdata.gmall.realtime.common.Constant;
import com.atguigu.bigdata.gmall.realtime.util.AtguiguUtil;
import com.atguigu.bigdata.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2022/10/17 13:46
 */
public class Dws_04_DwsUserUserLoginWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_04_DwsUserUserLoginWindow().init(
            4004,
            2,
            "Dws_04_DwsUserUserLoginWindow",
            Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
        
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        // 1. 过滤登录页面记录
        SingleOutputStreamOperator<JSONObject> loginPageStream = findLoginPage(stream);
        // 2. 转成 pojo 类型
        SingleOutputStreamOperator<UserLoginBean> beanStream = parseToObject(loginPageStream);
        beanStream.print("beanStream");
        // 3. 开窗聚合
        SingleOutputStreamOperator<UserLoginBean> resultStream = windowAndAgg(beanStream);
        resultStream.print("resultStream");
        // 4. 写出到 clickhouse 中
        writeToClickHouse(resultStream);
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<UserLoginBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_user_user_login_window", UserLoginBean.class));
    }
    
    private SingleOutputStreamOperator<UserLoginBean> windowAndAgg(
        SingleOutputStreamOperator<UserLoginBean> beanStream) {
        return beanStream  // 过滤后的数据:
            
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .aggregate(
                new AggregateFunction<UserLoginBean, Tuple2<Long, Long>, UserLoginBean>() {
                    // 初始化累加器
                    @Override
                    public Tuple2<Long, Long> createAccumulator() {
                        // 执行几次: keyBy 每个窗口每个 key 执行一次
                        // 没有 key: 每个窗口执行一次
                        return Tuple2.of(0L, 0L);
                    }
                    
                    // 累加的方法
                    @Override
                    public Tuple2<Long, Long> add(UserLoginBean bean, Tuple2<Long, Long> acc) {
                        // 每来一个元素执行一次
                        // acc.f0 存储 uuCt  acc.f1 存储 backCt
                        return Tuple2.of(acc.f0 + bean.getUuCt(), acc.f1 + bean.getBackCt());
                    }
                    
                    // 返回累加的结果
                    @Override
                    public UserLoginBean getResult(Tuple2<Long, Long> acc) {
                        // 触发窗口计算的时候执行一次!
                        return new UserLoginBean("", "", acc.f1, acc.f0, System.currentTimeMillis());
                    }
                    
                    // 累加器的合并: 当前面的窗口是 session 的窗口的时候才会执行
                    @Override
                    public Tuple2<Long, Long> merge(Tuple2<Long, Long> a, Tuple2<Long, Long> b) {
                        return null;
                    }
                },
                new ProcessAllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                    @Override
                    public void process(Context ctx,
                                        Iterable<UserLoginBean> elements,
                                        Collector<UserLoginBean> out) throws Exception {
                        UserLoginBean bean = elements.iterator().next();
                        
                        bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));
                        out.collect(bean);
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<UserLoginBean> parseToObject(SingleOutputStreamOperator<JSONObject> loginPageStream) {
        return loginPageStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
                    .withIdleness(Duration.ofSeconds(20))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("uid"))
            .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {
                
                private ValueState<String> lastVisitDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastVisitDateState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<String>("lastVisitDateState",
                                                                   String.class
                        ));
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<UserLoginBean> out) throws Exception {
                    Long ts = obj.getLong("ts");
                    
                    
                    long backCt = 0L;
                    long uuCt = 0L;
                    // TODO
                    String today = AtguiguUtil.toDate(ts);
                    String lastVisitDate = lastVisitDateState.value();
                    if (!today.equals(lastVisitDate)) {
                        // 今天的第一次登录
                        uuCt = 1L;
                        lastVisitDateState.update(today);
                        
                        // 需要判断是否为7 日回流用户
                        if (lastVisitDate != null) {
                            // 证明以前登录过, 需要判断是否为 回流
                            if ((ts - AtguiguUtil.dateToTs(lastVisitDate)) / 1000 / 60 / 60 / 24 >= 7) {
                                backCt = 1L;
                            }
                        }
                    }
                    UserLoginBean bean = new UserLoginBean("", "",
                                                           backCt, uuCt,
                                                           ts
                    );
                    
                    if (uuCt == 1) {
                        out.collect(bean);
                    }
                }
            });
    }
    
    private SingleOutputStreamOperator<JSONObject> findLoginPage(DataStreamSource<String> stream) {
        return stream
            .map(JSON::parseObject)
            .filter(new FilterFunction<JSONObject>() {
                @Override
                public boolean filter(JSONObject obj) throws Exception {
                    String uid = obj.getJSONObject("common").getString("uid");
                    String lastPageId = obj.getJSONObject("page").getString("last_page_id");
                    
                    return uid != null && (lastPageId == null || "login".equals(lastPageId));
                }
            });
    }
}
/*
 用户域用户登陆各窗口汇总表
 统计七日回流用户和当日独立用户数。
 
 数据源:
    页面日志
    
    过滤出登陆记录
    
    当日独立用户
    
    七日回流
        今天登陆, 上次登录是在 7 天前
        
    搞一个状态, 记录上一次登陆日期.

登陆记录:
    如何找出来
    
        自动登陆
            访问一个页面, uid 非 null, 并且 last_page_id is nul
            
            uid != null && last_page_id= nul
        
        访问的过程中, 碰到一些操作, 需要登陆, 会调整到登录页面, 然后登陆, ...
            a -> login -> a(其他页面)
                uid != null && last_page_id="login"
                
 */